package cn.sc.summer.auth.handler;

import cn.hutool.extra.spring.SpringUtil;
import cn.sc.summer.constant.model.Result;
import cn.sc.summer.constant.util.ConvertUtil;
import cn.sc.summer.token.service.EncryptService;
import cn.sc.summer.token.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * 类名：登录失败处理拦截器
 *
 * @author a-xin
 * @date 2023/11/24 09:47
 */
@Slf4j
public class LoginFailHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        exception.printStackTrace();
        EncryptService encryptService = SpringUtil.getBean(EncryptService.class);
        String encrypt = encryptService.encrypt(request, ConvertUtil.toJsonString(Result.fail(exception.getMessage(), exception.getMessage())));
        ResponseUtil.writeFailed(response, new HashMap<>(), encrypt);
    }

}
